package com.jtech.together.view.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageButton;
import android.widget.TextView;

import com.jtech.together.R;
import com.jtech.together.manager.UserManager;
import com.jtech.together.model.UserModel;
import com.jtech.together.mvp.contract.ProfileCompleteContract;
import com.jtech.together.mvp.presenter.ProfileCompletePresenter;
import com.jtech.together.util.ActivityJump;
import com.jtech.together.util.ImageSelect;
import com.jtech.together.util.ImageUtils;
import com.jtech.together.util.SexUtil;
import com.jtech.together.util.Util;
import com.jtech.together.view.activity.base.BaseActivity;
import com.jtech.together.view.weight.dialog.BirthdayDialog;
import com.jtech.together.view.weight.dialog.CustomProgressDialog;
import com.jtech.together.view.weight.dialog.SexDialog;
import com.umeng.analytics.MobclickAgent;

import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 用户信息完善页面
 * Created by wuxubaiyang on 2017/5/10.
 */
public class ProfileCompleteActivity extends BaseActivity implements ProfileCompleteContract.View, Toolbar.OnMenuItemClickListener, TextView.OnEditorActionListener {
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.imagebutton_profile_complete_avatar)
    ImageButton imageButtonAvatar;
    @Bind(R.id.textinputlayout_profile_complete_nickname)
    TextInputLayout textInputLayoutNickName;
    @Bind(R.id.textinputlayout_profile_complete_bio)
    TextInputLayout textInputLayoutBio;
    @Bind(R.id.textview_profile_complete_sex)
    TextView textViewSex;
    @Bind(R.id.textview_profile_complete_birthday)
    TextView textViewBirthday;

    private ProfileCompleteContract.Presenter presenter;
    private String avatarUrl;
    private long birthday;
    private int sex;

    @Override
    protected void initVariables(Bundle bundle) {
        //绑定P类
        presenter = new ProfileCompletePresenter(getActivity(), this, bundle);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setContentView(R.layout.activity_profile_complete);
        //设置标题栏
        setSupportActionBar(toolbar);
        //设置标题栏菜单点击事件
        toolbar.setOnMenuItemClickListener(this);
        //设置输入监听
        textInputLayoutNickName.getEditText()
                .addTextChangedListener(new OnTextChangeListener(textInputLayoutNickName));
        textInputLayoutBio.getEditText()
                .addTextChangedListener(new OnTextChangeListener(textInputLayoutBio));
        //设置键盘动作监听
        textInputLayoutBio.getEditText()
                .setOnEditorActionListener(this);
    }

    @Override
    protected void loadData() {
        //设置用户信息
        setUserProfile(UserManager.getCurrentUser());
    }

    /**
     * 设置默认用户信息
     *
     * @param userModel
     */
    private void setUserProfile(UserModel userModel) {
        //设置默认昵称
        textInputLayoutNickName.getEditText()
                .setText(userModel.getNickname());
    }

    /**
     * 提交信息
     */
    private boolean submit() {
        //判断头像是否为空
        if (TextUtils.isEmpty(avatarUrl)) {
            Snackbar.make(toolbar, "请选择头像", Snackbar.LENGTH_SHORT).show();
            return false;
        }
        //判断昵称是否为空
        String nickName = textInputLayoutNickName.getEditText()
                .getText().toString();
        if (TextUtils.isEmpty(nickName)) {
            textInputLayoutNickName.setError("昵称不能为空");
            return false;
        }
        //判断个人简介是否为空
        String bio = textInputLayoutBio.getEditText()
                .getText().toString();
        if (TextUtils.isEmpty(bio)) {
            textInputLayoutBio.setError("简介不能为空");
            return false;
        }
        //判断性别是否为空
        String sexStr = textViewSex.getText().toString();
        if (TextUtils.isEmpty(sexStr)) {
            Snackbar.make(toolbar, "性别不能为空", Snackbar.LENGTH_SHORT).show();
            return false;
        }
        //判断生日是否为空
        String birthdayStr = textViewBirthday.getText().toString();
        if (TextUtils.isEmpty(birthdayStr)) {
            Snackbar.make(toolbar, "生日不能为空", Snackbar.LENGTH_SHORT).show();
            return false;
        }
        //提交修改
        presenter.modifyProfile(avatarUrl, nickName, bio, sex, birthday);
        CustomProgressDialog.showProgressDialog(getActivity(), "正在完善信息");
        return true;
    }

    /**
     * 跳过设置
     */
    private void skipSetting() {
        new AlertDialog.Builder(getActivity())
                .setTitle("Info")
                .setMessage("跳过后可以在个人页面继续设置哦!")
                .setNegativeButton("取消", null)
                .setPositiveButton("跳过", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ActivityJump.build(getActivity(), MainActivity.class)
                                .jump();
                        onBackPressed();
                    }
                }).show();
    }

    @Override
    public void avatarUpdateSuccess(String avatarUrl) {
        this.avatarUrl = avatarUrl;
    }

    @Override
    public void modifySuccess() {
        CustomProgressDialog.dismissProgressDialog();
        ActivityJump.build(getActivity(), MainActivity.class)
                .jump();
        onBackPressed();
    }

    @Override
    public void modifyFail(String error) {
        CustomProgressDialog.dismissProgressDialog();
        Snackbar.make(toolbar, error, Snackbar.LENGTH_SHORT).show();
    }

    @OnClick({R.id.imagebutton_profile_complete_avatar,
            R.id.linearlayout_profile_complete_sex,
            R.id.linearlayout_profile_complete_birthday})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imagebutton_profile_complete_avatar://头像选择事件
                ImageSelect.singleSelect(getActivity(), true);
                break;
            case R.id.linearlayout_profile_complete_sex://性别选择
                SexDialog.build(getActivity())
                        .setOnClickListener(new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //存储性别选择
                                sex = which;
                                //显示性别
                                textViewSex.setText(SexUtil.getSex(sex));
                            }
                        }).show();
                break;
            case R.id.linearlayout_profile_complete_birthday://生日选择
                BirthdayDialog.build(getActivity())
                        .setBirthdaySelectDoneListener(new BirthdayDialog.OnBirthdaySelectDoneListener() {
                            @Override
                            public void onSelectDone(long birthday, int year, int month, int dayOfMonth) {
                                if (Util.isBornFuture(birthday)) {
                                    Snackbar.make(toolbar, "您老要在未来诞生么~", Snackbar.LENGTH_SHORT).show();
                                    return;
                                }
                                ProfileCompleteActivity.this.birthday = birthday;
                                textViewBirthday.setText(Util.formatBirthday(birthday) + "\t(" + Util.getAge(birthday) + "岁)");
                            }
                        })
                        .setDefaultTime(birthday)
                        .show();
                break;
        }
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.done://完成
                return submit();
            case R.id.close://跳过
                skipSetting();
                return true;
        }
        return false;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        toolbar.inflateMenu(R.menu.menu_profile_complete);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            return submit();
        }
        return false;
    }

    /**
     * 当输入变化的时候
     */
    private class OnTextChangeListener implements TextWatcher {
        private TextInputLayout textInputLayout;

        public OnTextChangeListener(TextInputLayout textInputLayout) {
            this.textInputLayout = textInputLayout;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //清空错误
            if (!TextUtils.isEmpty(textInputLayout.getError())) {
                textInputLayout.setError("");
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //判断是否为图片选择返回
        if (ImageSelect.isRequestImageResult(requestCode, resultCode)) {
            List<String> urls = ImageSelect.getRequestImage(data);
            if (null != urls && urls.size() > 0) {
                String avatarUrl = urls.get(0);
                //显示头像
                ImageUtils.showCircleImage(getActivity(), avatarUrl, imageButtonAvatar,
                        R.drawable.ic_default_avatar, R.drawable.ic_default_avatar);
                //存储头像路径
                this.avatarUrl = avatarUrl;
            }
        }
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(TAG);
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(TAG);
        MobclickAgent.onPause(this);
    }
}